import { useUserStore } from "@/store/modules/user";
import { useCommonStore } from "@/store";
const baseURL = import.meta.env.VITE_APP_API_BASE_URL;
// 标记是否正在刷新token
let isHandlingTokenExpired = false;
// 存储待重发请求的队列
let requests = [];
const request = (options) => {
  const userStore = useUserStore();
  const commonStore = useCommonStore();

  return new Promise((resolve, reject) => {
    uni.request({
      url: baseURL + options.url,
      method: options.method || "GET",
      data: options.data,
      header: {
        "Content-Type": "application/json",
        authorization: userStore.token ? `${userStore.token}` : "",
        longitude: commonStore.locationInfo.longitude || `10`, //经纬度
        latitude: commonStore.locationInfo.latitude || `30`,
        ...options.header,
      },
      success: (res) => {
        if (res.statusCode == 200) {
          if (res.data.code == "401") {
            console.log("需要重新登录：", res.data);
            handleTokenExpired();
            reject(res.data.msg || "请登录哦！");
          } else {
            resolve(res.data);
          }
        } else {
          // 其他业务错误
          uni.showToast({
            title: res.data.message || "请求失败",
            icon: "none",
          });
          reject(new Error(res.data.message || "请求失败"));
        }
      },
      fail: (err) => {
        uni.showToast({
          title: "网络错误",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

// 处理 token 过期
const handleTokenExpired = () => {
  if (isHandlingTokenExpired) {
    console.log('正在处理token过期，跳过重复处理');
    return;
  }

  isHandlingTokenExpired = true;
  const userStore = useUserStore();

  try {
    // 清除用户信息
    userStore.logout();

    // 获取当前页面路径
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const currentPath = `/${currentPage.route}`;

    console.log("当前页面路径:", currentPath);

    // 如果当前不在登录页，则跳转到登录页
    if (currentPath !== "/pages/login/index") {
      console.log('跳转到登录页');
      uni.navigateTo({
        url: "/pages/login/index",
        success: () => {
          console.log('跳转登录页成功');
        },
        fail: (err) => {
          console.error('跳转登录页失败:', err);
          // 如果navigateTo失败，尝试使用reLaunch
          uni.reLaunch({
            url: "/pages/login/index",
            success: () => {
              console.log('使用reLaunch跳转登录页成功');
            },
            fail: (reLaunchErr) => {
              console.error('reLaunch跳转登录页也失败:', reLaunchErr);
            }
          });
        },
        complete: () => {
          setTimeout(() => {
            isHandlingTokenExpired = false;
            console.log('重置token处理状态');
          }, 2000); // 增加延迟时间，避免重复处理
        },
      });
    } else {
      console.log('当前已在登录页，无需跳转');
      isHandlingTokenExpired = false;
    }
  } catch (error) {
    console.error('处理token过期时发生错误:', error);
    isHandlingTokenExpired = false;
  }
};

export default request;
